package com.company.controller;

import com.company.model.User;
import com.company.service.LoginService;
import com.company.service.ValidateService;
import com.company.utils.MessageResponse;
import com.company.validate.ValidateStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@RestController
public class LoginController {
    @GetMapping("/login/user")
    public MessageResponse<String> loginUserName(HttpSession session) {
        return LoginService.loginUserName(session);
    }

    @GetMapping("/login/code")
    public void createCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        ValidateService.createCode(request, response, session);
    }

    @PostMapping("/login/user")
    public MessageResponse<Boolean> loginUser(@RequestBody Map<String, Object> paramsMap, HttpSession session) {
        User user = User.fromMap((Map<String, Object>) paramsMap.get("user"));
        String validateCode = (String)paramsMap.get("validateCode");
        ValidateStatus status = ValidateService.validateCode(session, validateCode);

        System.out.println("Fuck");
        System.out.println(session.getAttribute(ValidateService.SESSION_KEY_IMAGE_CODE));
        if(status == ValidateStatus.SUCCESS) {
            return LoginService.loginUser(user, session);
        } else {
            return new MessageResponse<>(
                    status.toString(),
                    false
            );
        }
    }

    @PostMapping("/login/admin")
    public MessageResponse<Boolean> loginAdmin(@RequestBody Map<String, Object> paramsMap, HttpSession session) {
        User user = User.fromMap((Map<String, Object>) paramsMap.get("user"));
        String validateCode = (String)paramsMap.get("validateCode");

        ValidateStatus status = ValidateService.validateCode(session, validateCode);
        if(status == ValidateStatus.SUCCESS) {
            return LoginService.loginAdmin(user, session);
        } else {
            return new MessageResponse<>(
                    status.toString(),
                    false
            );
        }

    }

    @DeleteMapping("/login")
    public MessageResponse<Boolean> exit(HttpSession session) {
     return LoginService.exit(session);
    }
}
